<template>
  <div :class="$style.container">
    <topbar :nextAction="save" title="Shipping Address" rightTitle="Save"></topbar>
    <div>
      <header :class="$style.header">
        <h3>New Shipping Address</h3>
        <p>
          Please provide an accurate shipping address to ensure timely delivery.
        </p>
      </header>
      <field
        v-for="(item, key) in addressStruct"
        :label="key"
        v-model="formModel[key]"
      />
      <div :class="$style.part2">
        <div :class="['table-row', $style.list]">
          <div class="cell middle">
            Country
          </div>
          <div class="cell middle text-right">
            <small>{{countryInfo.countryString}}</small>
            <img :src="countryInfo.icon">
          </div>
        </div>
        <div :class="['table-row', $style.list]">
          <div class="cell middle">
            Set as defult address
          </div>
          <div class="cell middle text-right">
            <v-switch v-model="uadPrimary" />
          </div>
        </div>
      </div>
      <v-button v-if="addressId" type="danger" flat @click="confirm">Delete</v-button>
      <modal
        v-model="showModal"
        @on-confirm="deleteAddressById"
        title="Reminder"
        cancelText="Cancel"
        okText="Delete"
      >
        <div :class="$style.modalContent">
          Are you sure you want to delete this address?
        </div>
      </modal>
      <loading :show="loading" />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { toast, loading, topbar, field, vSwitch, button, modal } from 'components'
import { validator } from 'utils'

const countrySimpleName = 'IN'
const findCountryByName = (array, simpleName) =>
  array.filter(item => item.countrySimpleName === simpleName)[0]

export default {
  name: 'address',
  components: {
    toast,
    loading,
    topbar,
    field,
    vSwitch,
    vButton: button,
    modal,
  },
  computed: {
    ...mapState({
      addressStruct: state => state.address.addressStruct,
      loading: state => state.address.loading,
    }),
  },
  data() {
    return {
      formModel: {},
      name: '',
      showModal: false,
      uadPrimary: false,
      countryInfo: {},
    }
  },
  created() {
    this.addressId = this.$route.query.addressId

    if (this.addressId) {
      this.$store.dispatch('getAddressById', this.addressId)
        .then((res) => {
          this.setFormModel(res.data.data)
          this.uadPrimary = !!res.data.default
        })
    } else {
      this.$store.dispatch('getAddressStruct')
        .then((res) => {
          this.setFormModel(res.info)
        })
    }

    this.$store.dispatch('getCountry')
      .then((res) => {
        this.countryInfo = findCountryByName(res, countrySimpleName)
      })
  },
  methods: {
    setFormModel(obj) {
      const ret = {}
      const keys = Object.keys(obj)

      for (let i = 0, l = keys.length; i < l; i += 1) {
        ret[keys[i]] = obj[keys[i]].value
      }

      this.formModel = { ...this.formModel, ...ret }
    },
    confirm() {
      this.showModal = true
    },
    deleteAddressById() {
      this.$store.dispatch('deleteAddressById', this.addressId)
        .then((res) => {
          toast(res.info)
          if (res.code === 1000) {
            this.$router.replace({
              path: '/addressList',
            })
          }
        })
    },
    validAllField(addressStruct, formModel) {
      const ret = {}
      const keys = Object.keys(addressStruct)

      for (let i = 0, l = keys.length; i < l; i += 1) {
        if (!validator(formModel[keys[i]], addressStruct[keys[i]].rule)) {
          toast(`Please fill in ${keys[i]} completely.`)
          return false
        }

        ret[addressStruct[keys[i]].inputField] = formModel[keys[i]]
      }

      return ret
    },
    save() {
      const payload = this.validAllField(this.addressStruct, this.formModel)

      if (payload) {
        this.$store.dispatch('saveAddress', {
          ...payload,
          addressId: this.addressId,
          uad_primary: this.uadPrimary ? 1 : 0,
        })
          .then((res) => {
            toast(res.info)
            if (res.code === 1000) {
              this.$router.replace({
                path: '/addressList',
              })
            }
          })
      }
    },
  },
}
</script>

<style lang="scss" module>
.container {
  background-color: #f7f7f7;
}

.header {
  background-color: #5698f3;
  height: 70px;
  color: #fff;
  padding: 12px 24px;
  h3 {
    color: inherit;
    font-size: 16px;
    line-height: 14px;
  }
  p {
    font-size: 12px;
    line-height: 14px;
    margin-top: 5px;
  }
}

.part2 {
  margin: 12px 0;
}

.list {
  background-color: #fff;
  height: 48px;
  padding: 0 12px;
  font-size: 16px;
  small {
    color: #9B9B9B;
    font-size: 12px;
  }
  img {
    width: 30px;
    height: 20px;
    vertical-align: middle;
    margin-left: 6px;
  }
}

.modalContent {
  padding: 24px;
}
</style>
